﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';
    var vm = new Vue({
        el: '#app',
        data: {
            // 角色与权限
            devicePermission: true, // 能进到本页面，就是true
            deviceAddPermission: false,
            deviceDeletePermission: false,
            deviceEditPermission: false,
            multiDepartmentPermission: false,

            // 主页面
            filterName: '',
            dialogVisible: false, // 创建用户对话框，是否显示
            dialogTitle: '新建设备',
            actionType: '新建',
            tableData: [],
            formLabelWidth: '80px',
            department: null,   // 当前科室
            room: null, // 当前诊室
            treeData: [],
            currentPage: 1,
            totalCount: 0,
            pageSize: 10,
            selectedRows: [],

            device: {
                id: null,
                name: null,
                deviceTypeId: null,
                outerCode: null,
                manufacturer: null,
                model: null,
                aETitle: null,
                isActive: null,
                status:0, // 默认设备状态为 "运行"
                desc: null,
                order:null   
            },

            deviceTypeOptions: [],
            schduleOptions:[], // 排班计划选项

            statusOptions:[],

            defaultProps: {     // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },

            // 验证规则
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ],
                outerCode: [
                    { required: true, message: '请输入编号', trigger: 'blur' }
                ],
                deviceType: [
                    { required: true, message:'请选择设备类型',trigger:'blur' }
                ]
            }
        },
        computed: {
            tableShow: function () {
                var vm = this;
                if ((vm.treeData[0] && vm.treeData[0].children.length > 0) || vm.department) {
                    return true;
                }
                return false;
            },
            tableContanierTitle: function () {
                var vm = this;
                if (vm.department && vm.room) {
                    return `${vm.department.name} . ${vm.room.name}`;
                }
            }
        },
        methods: {

            // 根据科室加载设备类型
            loadDeviceTypeOptions() {
                var vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/device/get-device-type-options?depId=${vm.department.id}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.deviceTypeOptions = res.data;
                    }
                })
            },

            // 加载设备状态选项
            loadStatusOptions() {
                var vm = this;
                abp.ajax({
                    type: 'get',
                    url: '/api/device/get-status-options'
                }).then(res => {
                    if (res.code === 0) {
                        vm.statusOptions = res.data;
                    }
                });
            },

            // 打开设备类型详情
            gotoDeviceTypeDetail(id) {
                window.location.href = `/DeviceTypes/id=${id}`;
            },

            // 加载诊室下设备列表
            loadRoomDevices(id) {
                var vm = this;
                abp.ajax({
                    type: 'GET',
                    url: `/api/device/get-room-devices?roomId=${vm.room.id}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.tableData = res.data;
                    }
                });
            },

            // 加载可选排班计划选项
            loadScheduleOptions(id) {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url:`/api/device/get-schedule-options?deviceId=${id}`
                    }).then(res => {
                        if (res.code === 0) {
                            vm.schduleOptions = res.data;
                        }
                        resolve();
                    })
                });
            },

            // 加载设备详情
            loadDevice(id) {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/device/get?id=${id}`
                    }).then(res => {
                        if (res.code === 0) {
                            vm.device = res.data;
                            resolve();
                        }
                    });
                });
            },

            // 打开创建用户窗口
            showCreate() {
                var vm = this;
                vm.dialogTitle = "新建设备";
                vm.actionType = "新建";
                vm.device.isActive = true;
                vm.device.status = 0;
                vm.dialogVisible = true;
                vm.device.deviceTypeId = vm.deviceTypeOptions[0].value;
                vm.device.order = 0;
            },

            // 新建提交
            submitCreate() {
                var vm = this;
                vm.device.code = vm.deleteDevice.outerCode;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/device/submit-create?roomId=${vm.room.id}`,
                            data: JSON.stringify(vm.device)
                        }).then(res => {
                            if (res.code == 0) {
                                vm.resetForm();
                                vm.loadRoomDevices();
                                abp.notify.success(res.msg);
                            }
                            else {
                                abp.message.error(res.msg);
                            }
                        });
                    }
                });

            },

            // 打开编辑对话框
            showEdit(id) {
                var vm = this;
                vm.dialogTitle = "编辑设备";
                vm.actionType = "编辑";
                vm.loadScheduleOptions(id).then(() => {
                    vm.loadDevice(id).then(() => {
                        vm.dialogVisible = true;
                    })
                })
            },

            submitEdit() {
                var vm = this;
                vm.$refs['dialogForm'].validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/device/submit-edit?roomId=${vm.room.id}`,
                            data: JSON.stringify(vm.device)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.resetForm();
                                vm.loadRoomDevices();
                            }
                        });
                    }
                });
            },

            save() {
                var vm = this;
                if (vm.actionType === '新建') {
                    vm.submitCreate();
                }
                else {
                    vm.submitEdit();
                }
            },

            // 加载科室
            loadDepartment() {
                return new Promise(resolve => {
                    if (!vm.multiDepartmentPermission) {
                        // 获取当前登录科室
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-current-user-department"
                        }).then(res => {
                            vm.department = res;
                            resolve();
                        });
                    }
                    else {
                        resolve();
                    }
                });
            },

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                var vm = this;
                return new Promise(resolve => {
                    var url = `/api/device/get-tree-data?depId=${null}`;
                    if (vm.department) {
                        url = `/api/device/get-tree-data?depId=${vm.department.id}`
                    }
                    abp.ajax({
                        type: "GET",
                        url: url
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.treeData = res.data;
                            if (vm.treeData[0].children.length > 0) {
                                res.data[0].children.forEach((department, index) => {
                                    if (!vm.room && department && department.children && department.children.length > 0) {
                                        vm.room = vm.treeData[0].children[index].children[0];
                                        vm.department = department;
                                    }
                                })
                            }
                            else {
                                vm.tableShow = false;
                            }
                            resolve();
                        }
                    });
                });
            },

            // 删除设备
            deleteDevice(id) {
                var vm = this;
                abp.message.confirm("删除检查设备").then(confirmed => {
                    if (confirmed) {
                        abp.ajax({
                            type: 'Get',
                            url: `/api/device/delete?id=${id}`
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.loadRoomDevices();
                            }
                        });
                    }
                })
            },

            // 加载当前用户角色和权限.
            loadPermission() {
                var vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('DeviceGroup.Devices')) { // 科室用设备类型页面权限
                        vm.devicePermission = true;
                        if (abp.auth.isGranted('DeviceGroup.Devices.Add')) {// 添加现有设备类型
                            vm.deviceAddPermission = true;
                        }

                        if (abp.auth.isGranted('DeviceGroup.Devices.Delete')) { // 移除科室设备类型
                            vm.deviceDeletePermission = true;
                        }

                        if (abp.auth.isGranted('DeviceGroup.Devices.Edit')) { // 创建科室设备类型
                            vm.deviceEditPermission = true;
                        }
                    }
                    if (abp.auth.isGranted('OthersGoup.Others.MuMultiDepartment')) {
                        vm.multiDepartmentPermission = true;
                    }
                    resolve();
                });
            },

            // 点击科室
            nodeClicked(node,obj,bb) {
                if (node.icon != 'fa fa-hospital' && node.icon !='fa fa-building') {
                    var vm = this;
                    vm.room = node;
                    vm.department = obj.parent.data;
                    vm.loadDeviceTypeOptions();
                    vm.loadRoomDevices(vm.room.id);
                }
            },

            // 创建科室用用户，表单重置
            resetForm() {
                var vm = this;
                vm.$refs['dialogForm'].resetFields();
                vm.dialogVisible = false;
                Object.keys(vm.device).forEach(key => {
                    vm.device[key] = null;
                });
            },

            // 页面初始化
            init() {
                var vm = this;
                vm.loadStatusOptions();
                vm.loadPermission()
                    .then(() => {
                        vm.loadDepartment().then(() => {
                            vm.loadTreeData().then(() => {
                                vm.loadDeviceTypeOptions();
                                vm.loadRoomDevices();
                            });
                        });
                    });
            }
        },
        created() {
            var vm = this;
            vm.init();
        },
        mounted() {
        }
    });
});